package server

import (
	"context"
	"encoding/json"
	"errors"
	"gorm.io/gorm"
	"time"
	"user-srv/basic/config"
	l "user-srv/basic/init"
	__ "user-srv/basic/proto"
	"user-srv/handler/models"
	"user-srv/pkg"
)

// 用户注册
func (s *Server) RegisterUser(_ context.Context, in *__.RegisterUserReq) (*__.RegisterUserResp, error) {
	var user models.User
	if err := user.GetUserInfo(in.Mobile); err != nil {
		return nil, errors.New("获取用户数据失败")
	}
	if user.ID != 0 {
		return nil, errors.New("用户已存在")
	}
	user = models.User{
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
	}
	if err := user.RegisterUser(); err != nil {
		return nil, errors.New("用户注册失败")
	}
	return &__.RegisterUserResp{
		UserId: int64(user.ID),
	}, nil
}

// 用户登录
func (s *Server) LoginUser(_ context.Context, in *__.LoginUserReq) (*__.LoginUserResp, error) {
	var user models.User
	if err := user.GetUserInfo(in.Mobile); err != nil {
		return nil, errors.New("获取用户失败")
	}
	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	if user.Password != pkg.Md5(in.Password) {
		return nil, errors.New("密码错误")
	}
	return &__.LoginUserResp{
		UserId: int64(user.ID),
	}, nil
}

// 完善用户信息
func (s *Server) PerfectUser(_ context.Context, in *__.PerfectUserReq) (*__.PerfectUserResp, error) {
	var user models.User
	if err := user.GetUserById(int(in.UserId)); err != nil {
		return nil, errors.New("查看用户失败")
	}
	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	user = models.User{
		Model:    gorm.Model{ID: uint(in.UserId)},
		Username: in.Username,
		Email:    in.Email,
	}
	if err := user.PerfectUser(int(in.UserId)); err != nil {
		return nil, errors.New("用户完善信息失败")
	}
	return &__.PerfectUserResp{
		UserId: int64(user.ID),
	}, nil
}

// 用户展示
func (s *Server) ListUser(_ context.Context, in *__.ListUserReq) (*__.ListUserResp, error) {
	var user models.User
	list, _ := user.ListUser()
	var listUser []*__.ListUser
	get := config.Rdb.Get(l.Ctx, "userList").Val()
	if get == "" {
		for _, v := range list {
			listUser = append(listUser, &__.ListUser{
				UserId:   int64(v.ID),
				Mobile:   v.Mobile,
				Password: v.Password,
				Username: v.Username,
				Email:    v.Email,
			})
		}
		data, _ := json.Marshal(&listUser)
		config.Rdb.Set(l.Ctx, "userList", data, time.Minute*3)
	} else {
		_ = json.Unmarshal([]byte(get), &listUser)
	}

	return &__.ListUserResp{
		List: listUser,
	}, nil
}
